<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>河套灌区农业面源污染决策支持系统</title>
    <link rel="stylesheet" href="https://js.arcgis.com/4.28/esri/themes/light/main.css">
    <script src="https://js.arcgis.com/4.28/"></script>
    <!-- 将Chart.js移到head中，并添加onload事件 -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        /* 样式保持不变 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: "Microsoft YaHei", "微软雅黑", sans-serif;
        }
        
        body {
            background-color: #f5f5f5;
            color: #333;
            line-height: 1.6;
        }
        
        .header-container {
            background-color: rgb(0,135,60);
            color: white;
            padding: 15px 20px;
            display: flex;
            align-items: center;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            position: relative;
        }
        
        .xiaohui {
            position: absolute;
            top: 10px;
            left: 10px;
            display: block;
        }
        
        .title-container {
            flex: 1;
            text-align: center;
        }
        
        .chinese-title {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 5px;
            letter-spacing: 2px;
        }
        
        .english-title {
            font-size: 16px;
            letter-spacing: 1px;
        }
        
        .user-info {
            position: absolute;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            display: flex;
            align-items: center;
        }
        
        .welcome {
            margin-right: 15px;
            font-size: 16px;
        }
        
        button {
            font-size: 14px;
            padding: 5px 10px;
            border: 1px solid white;
            border-radius: 3px;
            background: transparent;
            color: white;
            cursor: pointer;
        }
        
        button:hover {
            background-color: rgba(255,255,255,0.2);
        }
        
        .container {
            max-width: 80%;
            margin: 0 auto;
            padding: 0 15px;
        }
        
        .navbar {
            background-color: #1a5f1a;
            padding: 10px 0;
        }
        
        .nav-menu {
            display: flex;
            justify-content: center;
            list-style: none;
            flex-wrap: wrap;
        }
        
        .nav-menu li {
            margin: 0 15px;
        }
        
        .nav-menu a {
            color: #fff;
            text-decoration: none;
            font-size: 16px;
            padding: 5px 10px;
            transition: all 0.3s;
        }
        
        .nav-menu a:hover {
            background-color: #0e4a0e;
            border-radius: 3px;
        }
        
        .main-content {
            display: flex;
            width: 100%;
            margin: 15px 0;
        }
        
        .sidebar {
            width: 200px;
            background-color: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            margin-right: 30px;
            flex: none; 
        }
        
        .sidebar-title {
            font-size: 18px;
            color: rgb(0,135,60);
            padding-bottom: 10px;
            border-bottom: 1px solid #e0e0e0;
            margin-bottom: 15px;
        }
        
        .sidebar-menu {
            list-style: none;
        }
        
        .sidebar-menu li {
            margin-bottom: 10px;
        }
        
        .sidebar-menu a {
            color: #333;
            text-decoration: none;
            display: block;
            padding: 8px 5px;
            transition: all 0.3s;
        }
        
        .sidebar-menu a:hover {
            color: #1a5f1a;
            background-color: #f0f0f0;
            border-radius: 3px;
        }
        
        .content {
            flex: 5;
            background-color: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        
        .content-title {
            font-size: 22px;
            color: #1a5f1a;
            padding-bottom: 15px;
            border-bottom: 1px solid #e0e0e0;
            margin-bottom: 20px;
        }
        
        .agriculture {
            text-align: center;
            display: block;
            margin-left: auto;
            margin-right: auto;
        }
        
        .footer {
            text-align: center;
            width: 100%;
            background-color: #1a5f1a;
            padding: 20px 0;
            border-top: 1px solid #e9ecef;
            color:#fff;
            margin-top: 30px;
        }
        
        @media (max-width: 768px) {
            .main-content {
                flex-direction: column;
            }
            
            .sidebar {
                width: 100%;
                margin-right: 0;
                margin-bottom: 20px;
            }
            
            .nav-menu {
                justify-content: flex-start;
                padding: 0 15px;
            }
            
            .nav-menu li {
                margin: 5px 10px;
            }
        }
        
        .sidebar-menu a.active {
            color: black;
            background-color: rgb(232, 230, 230);
            border-radius: 3px;
            font-weight: bold;
        }

        .sidebar-menu a.active:hover {
            background-color: rgb(232, 230, 230);
        }
        
        .container2 {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
        }

        h4 {
            text-align: center;
            color: #2c3e50;
            margin-bottom: 20px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #34495e;
        }

        input, select {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 16px;
            box-sizing: border-box;
        }

        button.calculate-btn {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 12px 24px;
            font-size: 16px;
            border-radius: 6px;
            cursor: pointer;
            width: 100%;
            font-weight: 600;
            transition: background-color 0.3s;
        }

        button.calculate-btn:hover {
            background-color: #45a049;
        }

        #results {
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #eee;
        }

        .hidden {
            display: none;
        }

        .loading {
            text-align: center;
            padding: 20px;
            font-style: italic;
            color: #7f8c8d;
        }

        .result-card {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            border-left: 4px solid #3498db;
        }

        .result-card h3 {
            margin-top: 0;
            color: #2c3e50;
        }

        .chart-container {
            margin-top: 20px;
            height: 300px;
        }

        .error {
            color: #e74c3c;
            padding: 15px;
            background: #fdeded;
            border-radius: 6px;
        }
        
        .scenario-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        
        .scenario-table th, .scenario-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: center;
        }
        
        .scenario-table th {
            background-color: #f2f2f2;
        }
        
        .scenario-table tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        
        .scenario-table tr:hover {
            background-color: #f1f1f1;
        }
        
        .best-scenario {
            background-color: #d4edda !important;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <!-- 头部区域 -->
    <div class="header-container">
        <!-- 校徽 -->
        <img src="../images/footer_logo.png"
             width="190px"
             height="60px"
             class="xiaohui">
        
        <!-- 标题 -->
        <div class="title-container">
            <div class="chinese-title">河套灌区农业面源污染决策支持系统</div>
            <div class="english-title">Decision Support System for Agricultural Non-Point Source Pollution in the Hetao Irrigation District</div>
        </div>
        
        <!-- 用户信息 -->
        <div class="user-info">
            <span class="welcome">用户您好</span>
            <button type="button" onclick="window.location.href='封面.html'">退出登录</button>
        </div>
    </div>
    
    <!-- 导航栏 -->
    <nav class="navbar">
        <div class="container">
            <ul class="nav-menu">
                <li><a href="#" onclick="window.location.href='../首页.html'">首页</a></li>
                <li><a href="#" onclick="window.location.href='weather.html'">属性数据</a></li>
                <li><a href="#" onclick="window.location.href='包气带介质类型.html'">空间数据</a></li>
                <li><a href="#" onclick="window.location.href='案例.html'">模型库</a></li>
                <li><a href="#" onclick="window.location.href='地表水环境质量标准.html'">知识库</a></li>
                <li><a href="#" onclick="window.location.href='相关网站.html'">相关网站</a></li>
            </ul>
        </div>
    </nav>
  
    <!-- 主要内容 -->
    <div class="container">
        <div class="main-content">
            <!-- 侧边栏 -->
            <aside class="sidebar">
                <h3 class="sidebar-title">模型库</h3>
                <ul class="sidebar-menu">
                    <li><a href="#" onclick="window.location.href='案例.html'">案例</a></li>
                    <li><a href="#" class="active" onclick="window.location.href='模拟.html'">模拟</a></li>
                    <li><a href="#" onclick="window.location.href='河套灌区农业面源污染负荷.html'">河套灌区农业面源污染负荷</a></li>
                </ul>
            </aside>
            
            <!-- 主要内容区 -->
            <main class="content">
                <h2 class="content-title">产量模拟计算器</h2>
                
                <div class="container2">
                    <form id="input-form">
                        <div class="form-group">
                            <label for="crop-type">作物类型:</label>
                            <select id="crop-type" required>
                                <option value="wheat">小麦</option>
                                <option value="maize">玉米</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label for="irrigation">灌溉量(mm):</label>
                            <input type="number" id="irrigation" step="0.1" required>
                        </div>

                        <div class="form-group">
                            <label for="nitrogen">施氮量(kg/公顷):</label>
                            <input type="number" id="nitrogen" step="0.1" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="rainfall">降水量(mm):</label>
                            <input type="number" id="rainfall" step="0.1" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="temperature">气温(℃):</label>
                            <input type="number" id="temperature" step="0.1" required>
                        </div>

                        <div class="form-group">
                            <label for="silt">土壤粉粒含量(%):</label>
                            <input type="number" id="silt" step="0.1" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="sand">土壤砂粒含量(%):</label>
                            <input type="number" id="sand" step="0.1" required>
                        </div>

                        <div class="form-group">
                            <label for="clay">土壤黏粒含量(%):</label>
                            <input type="number" id="clay" step="0.1" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="organic">土壤有机质含量(g/kg):</label>
                            <input type="number" id="organic" step="0.01" required>
                        </div>
                        
                        <button type="submit" class="calculate-btn">开始计算</button>
                    </form>
                    
                    <div id="results" class="hidden">
                        <h4>计算结果</h4>
                        <div id="loading" class="loading">计算中，请稍候...</div>
                        <div id="result-content"></div>
                        <div class="chart-container">
                            <canvas id="result-chart"></canvas>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>
      
    <!-- 页脚 -->
    <footer class="footer">
        <div class="container">
            <p>© 2025 河套灌区农业面源污染决策支持系统 版权所有</p>
        </div>
    </footer>

     <script>
        // 添加Chart.js加载检查
        function checkChartJS() {
            if (typeof Chart === 'undefined') {
                console.error('Chart.js未正确加载');
                return false;
            }
            console.log('Chart.js已加载，版本:', Chart.version);
            return true;
        }

        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            // 检查Chart.js是否加载
            if (!checkChartJS()) {
                console.warn('Chart.js加载失败，图表功能将不可用');
            }
            
            // 获取表单元素
            const form = document.getElementById('input-form');
            
            // 添加表单提交事件监听
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                
                // 显示加载状态
                document.getElementById('results').classList.remove('hidden');
                document.getElementById('loading').classList.remove('hidden');
                document.getElementById('result-content').innerHTML = '';
                
                // 收集表单数据
                const formData = {
                    crop: document.getElementById('crop-type').value,
                    irrigation: parseFloat(document.getElementById('irrigation').value),
                    nitrogen: parseFloat(document.getElementById('nitrogen').value),
                    rainfall: parseFloat(document.getElementById('rainfall').value),
                    temperature: parseFloat(document.getElementById('temperature').value),
                    silt: parseFloat(document.getElementById('silt').value),
                    sand: parseFloat(document.getElementById('sand').value),
                    clay: parseFloat(document.getElementById('clay').value),
                    organic: parseFloat(document.getElementById('organic').value)
                };
                
                console.log("发送的数据:", formData);
                
                // 发送数据到后端
                fetch('http://localhost:5194/calculate-scenarios', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                })
                .then(response => {
                    console.log("响应状态:", response.status);
                    
                    // 对于所有响应，都尝试解析为JSON
                    return response.json().then(data => {
                        if (!response.ok) {
                            // 如果响应不正常，抛出错误
                            throw new Error(data.error || `服务器错误: ${response.status}`);
                        }
                        return data;
                    });
                })
                .then(data => {
                    console.log("接收到的数据:", data);
                    
                    // 隐藏加载指示器
                    document.getElementById('loading').classList.add('hidden');
                    
                    // 显示结果
                    displayResults(data);
                })
                .catch(error => {
                    console.error("请求错误:", error);
                    document.getElementById('loading').classList.add('hidden');
                    document.getElementById('result-content').innerHTML = `
                        <div class="error">
                            <p>计算错误: ${error.message}</p>
                            <p>请检查您的输入并重试</p>
                            <p>如果问题持续存在，请联系系统管理员</p>
                        </div>
                    `;
                });
            });
        });
        
        // 显示结果的函数
        function displayResults(data) {
            console.log("显示结果函数被调用，数据:", data);
            
            const resultContent = document.getElementById('result-content');
            
            // 检查数据是否存在且包含必要的字段
            if (!data || !data.scenarios || !Array.isArray(data.scenarios)) {
                resultContent.innerHTML = `
                    <div class="error">
                        <h3>数据格式错误</h3>
                        <p>服务器返回的数据格式不正确，无法显示结果。</p>
                        <p>返回的数据: ${JSON.stringify(data)}</p>
                    </div>
                `;
                return;
            }
            
            // 确保有最佳方案索引
            const bestIndex = typeof data.best_scenario_index !== 'undefined' ? data.best_scenario_index : -1;
            
            // 创建情景表格
            let tableHTML = `
                <h3>不同削减比例情景分析</h3>
                <table class="scenario-table">
                    <thead>
                        <tr>
                            <th>削减比例</th>
                            <th>灌溉量(mm)</th>
                            <th>施氮量(kg/公顷)</th>
                            <th>预测产量(公斤/公顷)</th>
                            <th>灌溉水生产力(kg/m³)</th>
                            <th>偏氮肥生产力(kg/kg)</th>
                            <th>氮污染负荷(kg/公顷)</th>
                            <th>VIKOR得分</th>
                        </tr>
                    </thead>
                    <tbody>
            `;
            
            // 添加每个情景的数据行 - 使用安全的属性访问
            data.scenarios.forEach((scenario, index) => {
                const isBest = index === bestIndex;
                tableHTML += `
                    <tr ${isBest ? 'class="best-scenario"' : ''}>
                        <td>${(scenario.reduction_rate * 100).toFixed(0)}%</td>
                        <td>${scenario.irrigation ? scenario.irrigation.toFixed(1) : 'N/A'}</td>
                        <td>${scenario.nitrogen ? scenario.nitrogen.toFixed(1) : 'N/A'}</td>
                        <td>${scenario.yield ? scenario.yield.toFixed(1) : 'N/A'}</td>
                        <td>${scenario.iwp ? scenario.iwp.toFixed(3) : 'N/A'}</td>
                        <td>${scenario.pfpn ? scenario.pfpn.toFixed(1) : 'N/A'}</td>
                        <td>${scenario.nload ? scenario.nload.toFixed(1) : 'N/A'}</td>
                        <td>${scenario.vikor_score ? scenario.vikor_score.toFixed(4) : 'N/A'}</td>
                    </tr>
                `;
            });
            
            tableHTML += `
                    </tbody>
                </table>
            `;
            
            // 添加最佳方案信息
            if (bestIndex >= 0 && data.scenarios[bestIndex]) {
                const bestScenario = data.scenarios[bestIndex];
                tableHTML += `
                    <div class="result-card">
                        <h3>最佳方案推荐 (削减${(bestScenario.reduction_rate * 100).toFixed(0)}%)</h3>
                        <p>灌溉量: <strong>${bestScenario.irrigation ? bestScenario.irrigation.toFixed(1) : 'N/A'} mm</strong></p>
                        <p>施氮量: <strong>${bestScenario.nitrogen ? bestScenario.nitrogen.toFixed(1) : 'N/A'} kg/公顷</strong></p>
                        <p>预测产量: <strong>${bestScenario.yield ? bestScenario.yield.toFixed(1) : 'N/A'} 公斤/公顷</strong></p>
                        <p>灌溉水生产力: <strong>${bestScenario.iwp ? bestScenario.iwp.toFixed(3) : 'N/A'} kg/m³</strong></p>
                        <p>偏氮肥生产力: <strong>${bestScenario.pfpn ? bestScenario.pfpn.toFixed(1) : 'N/A'} kg/kg</strong></p>
                        <p>氮污染负荷: <strong>${bestScenario.nload ? bestScenario.nload.toFixed(1) : 'N/A'} kg/公顷</strong></p>
                    </div>
                `;
            } else {
                tableHTML += `<div class="error">无法确定最佳方案</div>`;
            }
            
            resultContent.innerHTML = tableHTML;
            // 在displayResults函数中添加调试信息
if (data.debug_info) {
    tableHTML += `
        <div class="result-card" style="background-color: #f0f8ff;">
            <h3>调试信息</h3>
            <p>使用的模型: ${data.debug_info.model_used || '未知'}</p>
            <p>最佳方案索引: ${data.debug_info.best_index || '未知'}</p>
            <p>最佳削减比例: ${data.debug_info.best_reduction_rate ? (data.debug_info.best_reduction_rate * 100).toFixed(0) + '%' : '未知'}</p>
            <p>VIKOR得分: ${data.debug_info.vikor_scores ? data.debug_info.vikor_scores.map(s => s.toFixed(4)).join(', ') : '未知'}</p>
        </div>
    `;
}
            // 显示图表 - 添加安全检查
            if (data.scenarios && data.scenarios.length > 0) {
                try {
                    renderChart(data.scenarios);
                } catch (chartError) {
                    console.error("图表渲染错误:", chartError);
                    // 添加错误信息到页面
                    resultContent.innerHTML += `
                        <div class="error">
                            <p>图表渲染失败: ${chartError.message}</p>
                            <p>数据表格仍可正常显示</p>
                        </div>
                    `;
                }
            }
        }
        
        // 渲染图表的函数 - 添加更安全的检查
        function renderChart(scenarios) {
            console.log("渲染图表函数被调用，情景数据:", scenarios);
            
            // 检查Chart.js是否可用
            if (typeof Chart === 'undefined') {
                throw new Error('Chart.js库未正确加载，无法绘制图表');
            }
            
            // 确保scenarios存在且是数组
            if (!scenarios || !Array.isArray(scenarios) || scenarios.length === 0) {
                throw new Error('无效的情景数据，无法绘制图表');
            }
            
            // 确保有canvas元素
            const canvas = document.getElementById('result-chart');
            if (!canvas) {
                throw new Error('找不到图表canvas元素');
            }
            
            const ctx = canvas.getContext('2d');
            if (!ctx) {
                throw new Error('无法获取canvas上下文');
            }
            
            // 准备图表数据
            const labels = scenarios.map(s => `削减${(s.reduction_rate * 100).toFixed(0)}%`);
            const yieldData = scenarios.map(s => s.yield || 0);
            const iwpData = scenarios.map(s => s.iwp || 0);
            const pfpnData = scenarios.map(s => s.pfpn || 0);
            const nloadData = scenarios.map(s => s.nload || 0);
            
            // 销毁现有的图表实例（如果存在）
            if (window.resultChart && typeof window.resultChart.destroy === 'function') {
                window.resultChart.destroy();
            }
            
            // 创建新图表
            window.resultChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [
                        {
                            label: '产量 (公斤/公顷)',
                            data: yieldData,
                            borderColor: 'rgba(76, 175, 80, 1)',
                            backgroundColor: 'rgba(76, 175, 80, 0.2)',
                            yAxisID: 'y',
                            fill: false,
                            tension: 0.1
                        },
                        {
                            label: '灌溉水生产力 (kg/m³)',
                            data: iwpData,
                            borderColor: 'rgba(54, 162, 235, 1)',
                            backgroundColor: 'rgba(54, 162, 235, 0.2)',
                            yAxisID: 'y1',
                            fill: false,
                            tension: 0.1
                        },
                        {
                            label: '偏氮肥生产力 (kg/kg)',
                            data: pfpnData,
                            borderColor: 'rgba(255, 206, 86, 1)',
                            backgroundColor: 'rgba(255, 206, 86, 0.2)',
                            yAxisID: 'y2',
                            fill: false,
                            tension: 0.1
                        },
                        {
                            label: '氮污染负荷 (kg/公顷)',
                            data: nloadData,
                            borderColor: 'rgba(255, 99, 132, 1)',
                            backgroundColor: 'rgba(255, 99, 132, 0.2)',
                            yAxisID: 'y3',
                            fill: false,
                            tension: 0.1
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: {
                        mode: 'index',
                        intersect: false
                    },
                    scales: {
                        y: {
                            type: 'linear',
                            display: true,
                            position: 'left',
                            title: {
                                display: true,
                                text: '产量 (公斤/公顷)'
                            }
                        },
                        y1: {
                            type: 'linear',
                            display: true,
                            position: 'right',
                            title: {
                                display: true,
                                text: '灌溉水生产力 (kg/m³)'
                            },
                            grid: {
                                drawOnChartArea: false
                            }
                        },
                        y2: {
                            type: 'linear',
                            display: false
                        },
                        y3: {
                            type: 'linear',
                            display: false
                        }
                    },
                    plugins: {
                        legend: {
                            position: 'top',
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false
                        }
                    }
                }
            });
            
            console.log("图表渲染完成");
        }
        
        // 添加页面卸载时的清理函数
        window.addEventListener('beforeunload', function() {
            if (window.resultChart && typeof window.resultChart.destroy === 'function') {
                window.resultChart.destroy();
            }
        });
    </script>
</body>
</html>